<template>
  <div v-if="visible" class="export-modal-overlay" @click="handleOverlayClick">
    <div class="export-modal" @click.stop>
      <div class="modal-header">
        <h3>导出对话</h3>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="modal-content">
        <!-- 导出格式选择 -->
        <div class="section">
          <label class="section-label">导出格式</label>
          <div class="format-grid">
            <div 
              v-for="format in exportFormats" 
              :key="format.value"
              class="format-card"
              :class="{ active: selectedFormat === format.value }"
              @click="selectedFormat = format.value">
              <div class="format-icon">{{ format.icon }}</div>
              <div class="format-name">{{ format.label }}</div>
              <div class="format-desc">{{ format.description }}</div>
            </div>
          </div>
        </div>

        <!-- 导出选项 -->
        <div class="section">
          <label class="section-label">导出选项</label>
          <div class="options-grid">
            <div class="option-item">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="exportOptions.includeTimestamps"
                  class="checkbox">
                <span class="checkmark"></span>
                包含时间戳
              </label>
            </div>
            <div class="option-item">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="exportOptions.includeMetadata"
                  class="checkbox">
                <span class="checkmark"></span>
                包含元数据
              </label>
            </div>
            <div class="option-item">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="exportOptions.onlyUserMessages"
                  class="checkbox">
                <span class="checkmark"></span>
                仅导出用户消息
              </label>
            </div>
            <div class="option-item">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="exportOptions.onlyAssistantMessages"
                  class="checkbox">
                <span class="checkmark"></span>
                仅导出AI回复
              </label>
            </div>
          </div>
        </div>

        <!-- 时间范围选择 -->
        <div class="section">
          <label class="section-label">时间范围</label>
          <div class="time-range">
            <div class="time-option">
              <label class="radio-label">
                <input 
                  type="radio" 
                  v-model="timeRange" 
                  value="all"
                  class="radio">
                <span class="radio-mark"></span>
                全部消息
              </label>
            </div>
            <div class="time-option">
              <label class="radio-label">
                <input 
                  type="radio" 
                  v-model="timeRange" 
                  value="today"
                  class="radio">
                <span class="radio-mark"></span>
                今天
              </label>
            </div>
            <div class="time-option">
              <label class="radio-label">
                <input 
                  type="radio" 
                  v-model="timeRange" 
                  value="custom"
                  class="radio">
                <span class="radio-mark"></span>
                自定义范围
              </label>
            </div>
          </div>
          
          <div v-if="timeRange === 'custom'" class="custom-time">
            <div class="time-input-group">
              <label>开始时间</label>
              <input 
                type="datetime-local" 
                v-model="customStartTime"
                class="time-input">
            </div>
            <div class="time-input-group">
              <label>结束时间</label>
              <input 
                type="datetime-local" 
                v-model="customEndTime"
                class="time-input">
            </div>
          </div>
        </div>

        <!-- 预览信息 -->
        <div class="section">
          <label class="section-label">导出预览</label>
          <div class="preview-info">
            <div class="preview-item">
              <span class="preview-label">消息数量:</span>
              <span class="preview-value">{{ filteredMessages.length }}</span>
            </div>
            <div class="preview-item">
              <span class="preview-label">预计文件大小:</span>
              <span class="preview-value">{{ estimatedFileSize }}</span>
            </div>
            <div class="preview-item">
              <span class="preview-label">导出格式:</span>
              <span class="preview-value">{{ getFormatDisplayName(selectedFormat) }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeModal">取消</button>
        <button 
          class="btn btn-primary" 
          @click="handleExport"
          :disabled="isExporting || filteredMessages.length === 0">
          <span v-if="isExporting" class="loading-spinner"></span>
          {{ isExporting ? '导出中...' : '开始导出' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  messages: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['close', 'export'])

// 导出格式选项
const exportFormats = ref([
  { 
    value: 'json', 
    label: 'JSON', 
    icon: '📄',
    description: '结构化数据，便于程序处理'
  },
  { 
    value: 'markdown', 
    label: 'Markdown', 
    icon: '📝',
    description: '易读格式，支持Markdown语法'
  },
  { 
    value: 'html', 
    label: 'HTML', 
    icon: '🌐',
    description: '网页格式，支持样式和链接'
  },
  { 
    value: 'pdf', 
    label: 'PDF', 
    icon: '📋',
    description: '便携文档，适合打印和分享'
  }
])

// 选中的格式
const selectedFormat = ref('json')

// 导出选项
const exportOptions = ref({
  includeTimestamps: true,
  includeMetadata: true,
  onlyUserMessages: false,
  onlyAssistantMessages: false
})

// 时间范围
const timeRange = ref('all')
const customStartTime = ref('')
const customEndTime = ref('')

// 导出状态
const isExporting = ref(false)

// 过滤后的消息
const filteredMessages = computed(() => {
  let filtered = [...props.messages]
  
  // 根据时间范围过滤
  if (timeRange.value === 'today') {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    
    filtered = filtered.filter(msg => {
      const msgTime = new Date(msg.timestamp)
      return msgTime >= today && msgTime < tomorrow
    })
  } else if (timeRange.value === 'custom') {
    if (customStartTime.value && customEndTime.value) {
      const startTime = new Date(customStartTime.value)
      const endTime = new Date(customEndTime.value)
      
      filtered = filtered.filter(msg => {
        const msgTime = new Date(msg.timestamp)
        return msgTime >= startTime && msgTime <= endTime
      })
    }
  }
  
  // 根据消息类型过滤
  if (exportOptions.value.onlyUserMessages) {
    filtered = filtered.filter(msg => msg.role === 'user')
  } else if (exportOptions.value.onlyAssistantMessages) {
    filtered = filtered.filter(msg => msg.role === 'assistant')
  }
  
  return filtered
})

// 估算文件大小
const estimatedFileSize = computed(() => {
  const messageCount = filteredMessages.value.length
  const avgMessageSize = 200 // 平均每条消息200字符
  
  let sizeInBytes = messageCount * avgMessageSize
  
  // 根据格式调整大小
  switch (selectedFormat.value) {
    case 'json':
      sizeInBytes *= 1.2 // JSON格式稍大
      break
    case 'html':
      sizeInBytes *= 1.5 // HTML包含样式
      break
    case 'pdf':
      sizeInBytes *= 0.8 // PDF压缩
      break
  }
  
  if (sizeInBytes < 1024) {
    return `${sizeInBytes} B`
  } else if (sizeInBytes < 1024 * 1024) {
    return `${(sizeInBytes / 1024).toFixed(1)} KB`
  } else {
    return `${(sizeInBytes / (1024 * 1024)).toFixed(1)} MB`
  }
})

// 获取格式显示名称
const getFormatDisplayName = (format) => {
  const formatObj = exportFormats.value.find(f => f.value === format)
  return formatObj ? formatObj.label : format.toUpperCase()
}

// 关闭模态框
const closeModal = () => {
  emit('close')
}

// 点击遮罩层关闭
const handleOverlayClick = () => {
  closeModal()
}

// 处理导出
const handleExport = async () => {
  if (filteredMessages.value.length === 0) {
    return
  }
  
  isExporting.value = true
  
  try {
    const exportData = {
      format: selectedFormat.value,
      options: exportOptions.value,
      timeRange: timeRange.value,
      customStartTime: customStartTime.value,
      customEndTime: customEndTime.value
    }
    
    emit('export', filteredMessages.value, exportData)
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    isExporting.value = false
  }
}

// 监听选项变化，确保互斥选项
watch(() => exportOptions.value.onlyUserMessages, (newVal) => {
  if (newVal) {
    exportOptions.value.onlyAssistantMessages = false
  }
})

watch(() => exportOptions.value.onlyAssistantMessages, (newVal) => {
  if (newVal) {
    exportOptions.value.onlyUserMessages = false
  }
})
</script>

<style scoped>
@import './index.css';
</style>
